package com.levi.aop;

import com.levi.annotation.Login;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author shentong
 * @since 2022/11/10 22:07
 */
@Aspect
@Component
@Slf4j
public class LoginAspect {

    @Pointcut("@annotation(com.levi.annotation.Login)"+
            "@within(com.levi.annotation.Login)"
    )
    public void loginPoint(){

    }

    @Around("loginPoint()")
    @SneakyThrows
    public Object around(ProceedingJoinPoint pjp){
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        MergedAnnotations annotations = MergedAnnotations.from(method, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY);
        if (annotations.isPresent(Login.class)) {
            log.info("该方法加了Login注解,需要登录后才能访问");
        }
       /* Login annotation = method.getAnnotation(Login.class);
        if (null != annotation) {
            log.info("该方法加了Login注解,需要登录后才能访问");
        }*/
        return pjp.proceed();
    }
}
